#include "mainwindow.h"
#include "ui_mainwindow.h"

/*

[2022-12-26 09:12:22.732]# RECV HEX FROM  :33286>
B0 A1 02 00 24 00 38 36 32 39 30 31 30 36 34 33 39 38 37 38 33 32 30 32 32 2D 31 32 2D 32 36 20 30 39 3A 31 32 3A 32 33 00 11 A7 FB

[2022-12-26 09:12:23.265]# RECV HEX FROM  :33286>
B0 A1 02 00 24 00 38 36 32 39 30 31 30 36 34 33 39 38 37 38 33 32 30 32 32 2D 31 32 2D 32 36 20 30 39 3A 31 32 3A 32 34 00 13 9A ED

[2022-12-26 09:12:23.772]# RECV HEX FROM  :33286>
B0 A1 02 00 24 00 38 36 32 39 30 31 30 36 34 33 39 38 37 38 33 32 30 32 32 2D 31 32 2D 32 36 20 30 39 3A 31 32 3A 32 34 00 05 6D 9F

[2022-12-26 09:12:24.313]# RECV HEX FROM  :33286>
B0 A1 00 00 23 00 38 36 32 39 30 31 30 36 34 33 39 38 37 38 33 32 30 32 32 2D 31 32 2D 32 36 20 30 39 3A 31 32 3A 32 35 00 23 34

##0279QN=20221226091428001;ST=51;CN=2011;PW=123456;MN=862901064398783000000000;Flag=4;CP=&&DataTime=20221226091428;a34041-Rtd=0.02,a34041-Flag=N;a34000-Rtd=0.03,a34000-Flag=N;a24088-Rtd=0.00,a24088-Flag=N;ga0601-Rtd=0.00,ga0601-Flag=N;ga2001-Rtd=0.00,ga2001-Flag=N;SB1-RS=0;SB2-RS=0;&&1400

*/

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);

    LOG_INIT();
    LOG_SUBSCRIBE(log_console_logger, LOG_TRACE_LEVEL);
    LOG_SUBSCRIBE(log_file_logger, LOG_TRACE_LEVEL);

    LOGD("%s, thread:0x%08X", __FUNCTION__, QThread::currentThreadId());

    if(!hvTcpServer.start(10123))
    {
        QMessageBox::critical(this, QApplication::applicationName(), tr("服务器启动失败，请检查10123端口是否被占用！"));
    }

    ui->channelListView->setModel(new QStringListModel(this));
    ui->channelListView->setSelectionMode(QListView::ExtendedSelection);
    ui->channelListView->setAlternatingRowColors(true);

    ui->deviceListView->setModel(new QStringListModel(this));
    ui->deviceListView->setSelectionMode(QListView::ExtendedSelection);
    ui->deviceListView->setAlternatingRowColors(true);

//    connect(ui->sendBtn, &QPushButton::clicked, this, [=](){
//        foreach(QModelIndex idx, ui->channelListView->selectionModel()->selectedRows())
//        {
//            QString peerAddress = ui->channelListView->model()->data(idx).toString();
//            hv::SocketChannelPtr channel = hvTcpServer.socketChannel(peerAddress);
//            if(channel)
//            {
//                QTextCodec* codec = QTextCodec::codecForName("GBK");
//                QByteArray data = codec->fromUnicode(ui->sendLineEdit->text());
//                channel->write(data.data(), data.size());
//            }
//        }
//    });

    connect(ui->sendBtn, &QPushButton::clicked, this, [=](){
        foreach(QModelIndex idx, ui->deviceListView->selectionModel()->selectedRows())
        {
            QString imei = ui->deviceListView->model()->data(idx).toString();
            hv::SocketChannelPtr channel = devices.value(imei);
            if(channel)
            {
                QTextCodec* codec = QTextCodec::codecForName("GBK");
                QByteArray data = codec->fromUnicode(ui->sendLineEdit->text());
                channel->write(data.data(), data.size());
            }
        }
    });

//    connect(ui->refreshBtn, &QPushButton::clicked, this, [=](){

//    });
}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::postEvent()
{
    QApplication::postEvent(this, new CustomEvent());
}

void MainWindow::postEvent(const DeviceHeartbeatEvent& event)
{
    QApplication::postEvent(this, new DeviceHeartbeatEvent(event));
}

void MainWindow::postEvent(const DisconnectEvent& event)
{
    QApplication::postEvent(this, new DisconnectEvent(event));
}

void MainWindow::postEvent(const ConnectEvent& event)
{
    QApplication::postEvent(this, new ConnectEvent(event));
}

void MainWindow::channelAdd(const QString &peerAddress, const hv::SocketChannelPtr& channel)
{
    channels[peerAddress] = channel;
    QStringListModel* model = static_cast<QStringListModel*>(ui->channelListView->model());
    QStringList l = model->stringList();
    l.append(peerAddress);
    model->setStringList(l);
}

void MainWindow::channelRemove(const QString &peerAddress)
{
    QStringListModel* model = static_cast<QStringListModel*>(ui->channelListView->model());
    QStringList l = model->stringList();
    if(l.contains(peerAddress))
    {
        l.removeOne(peerAddress);
        model->setStringList(l);
        channels.remove(peerAddress);
    }
}

void MainWindow::devicesAdd(const QString& peerAddress, const QString &imei, const hv::SocketChannelPtr& channel)
{
    devices.insert(imei, channel);
    mapping.insert(peerAddress, imei);

    QStringListModel* model = static_cast<QStringListModel*>(ui->deviceListView->model());
    QStringList l = model->stringList();
    if(!l.contains(imei))
    {
        l.append(imei);
        model->setStringList(l);
    }
}

void MainWindow::devicesRemove(const QString& peerAddress)
{
    QString imei = mapping.value(peerAddress);
    QStringListModel* model = static_cast<QStringListModel*>(ui->deviceListView->model());
    QStringList l = model->stringList();
    if(l.contains(imei))
    {
        l.removeOne(imei);
        model->setStringList(l);
        devices.remove(imei);
        mapping.remove(peerAddress);
    }
}

void MainWindow::customEvent(QEvent* event)
{
    if(event->type() == CSTM_EVENT_DEVICE_HEARTBEAT)
    {
        DeviceHeartbeatEvent* e = dynamic_cast<DeviceHeartbeatEvent*>(event);
        devicesAdd(QString(e->channel()->peeraddr().data()), e->imei(), e->channel());
    }else if(event->type() == CSTM_EVENT_CONNECT)
    {
        ConnectEvent* e = dynamic_cast<ConnectEvent*>(event);
        QString peerAddress(e->channel()->peeraddr().data());
        channelAdd(peerAddress, e->channel());
    }else if(event->type() == CSTM_EVENT_DISCONNECT)
    {
        DisconnectEvent* e = dynamic_cast<DisconnectEvent*>(event);
        QString peerAddress(e->channel()->peeraddr().data());
        channelRemove(peerAddress);
        devicesRemove(peerAddress);
    }
}
